package jmars.mobile.datainvetigation;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import jmars.mobile.common.PropertiesLoader;

public class CountPhoneNumber { 
	static String inputDir=PropertiesLoader.getProperty("inputDir");
	static String outputDir=PropertiesLoader.getProperty("outputDir");
	static String fileList=PropertiesLoader.getProperty("fileList");
	static String[] filenames;
	
	public static void main(String[] args) throws IOException {
		Resource r= new FileSystemResource(inputDir);
		if("".equals(fileList))filenames=null;
		else filenames=fileList.split(",");
		FilenameFilter fnf=new FilenameFilter(){
			@Override
			public boolean accept(File dir, String name) {
				if(filenames==null)return true;
				else for(String fn:filenames){
					if(fn.equals(name))return true;
				}
				return false;
			}
		};
		Long total = 0L;
		FileInputStream fis;
		BufferedReader reader;
		String row;
		String[] cols;
		FileWriter resultWriter;
		resultWriter = new FileWriter(outputDir+"\\totalPhoneNumbers.txt");
		Set<String> distinctPhoneNumber=new HashSet<String>();
		for(File inputFile:r.getFile().listFiles(fnf)){
			fis = new FileInputStream(inputFile);
			reader = new BufferedReader(new InputStreamReader(fis));
			while((row=reader.readLine())!=null){
				cols=row.split("\\|");
				if(!distinctPhoneNumber.contains(cols[0]))distinctPhoneNumber.add(cols[0]);
				total++;
			}
			reader.close();
			fis.close();
			System.out.println(inputFile.getName()+" finished at "+total);
		}
		resultWriter.write("phone numbers:"+distinctPhoneNumber.size()+"\r\n");
		resultWriter.write("total:"+total+"\r\n");
		resultWriter.write("total:"+total+"\r\n");
		resultWriter.close();
		System.out.println("All done.");
	}

}
